package com.ws.common.base.service.Impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ReflectUtil;
import cn.hutool.core.util.StrUtil;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.ws.common.base.dao.BaseMapper;
import com.ws.common.base.entity.Columns;
import com.ws.common.base.service.IBaseService;
import com.ws.common.base.service.IColumnsService;
import com.ws.common.util.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;

import java.lang.reflect.ParameterizedType;
import java.util.*;

public class BaseServiceImpl<T>  implements IBaseService<T> {

    @Autowired
    BaseMapper<T> baseMapper;
    @Autowired
    IColumnsService columnsService;

    @Override
    public Integer insertOrUpdate(T t) {
        String className=t.getClass().getSimpleName();
        List<Columns> columns=columnsService.selectColumnsByTableName(className);
        for(Columns column: columns){
            if(StrUtil.equals(column.getColumnKey(),"PRI")){
                String javaColumnNameMin=StringUtils.camelMin(column.getColumnName());
                Object o=BeanUtil.getFieldValue(t,javaColumnNameMin);
                if(StringUtils.objectIsNotEmpty(o)){
                    return this.updateSelective(t);
                }
                break;
            }
        }
        return this.insert(t);
    }

    @Override
    public Integer insert(T t) {
        setDefaultValu(t);
        String className=t.getClass().getSimpleName();
        List<Columns> columns=columnsService.selectColumnsByTableName(className);
        String field="";//字段
        String value="";//值
        for(Columns column: columns){
            field += ","+column.getColumnName();
            if(StrUtil.equals(column.getColumnKey(),"PRI")){
                String uuid=UUID.randomUUID().toString().replace("-","");

                Object o=BeanUtil.getFieldValue(t,StringUtils.camelMin(column.getColumnName()) );
                if(StringUtils.objectIsNotEmpty(o)){
                    uuid=(String)o;
                }
                value += ",'"+uuid+"' ";
            }else{
                value += ",#{t."+StringUtils.camelMin(column.getColumnName())+"} ";
            }
        }
        field=field.substring(1);
        value=value.substring(1);
        String tableName=StringUtils.camelToUnderline(className); //表名
        return baseMapper.insert(t,tableName,field,value);
    }

    @Override
    public Integer insertSelective(T t) {
        setDefaultValu(t);
        this.setDefaultValu(t);
        String className=t.getClass().getSimpleName();
        List<Columns> columns=columnsService.selectColumnsByTableName(className);
        String field="";//字段
        String value="";//值
        for(Columns column: columns){
            if(StrUtil.equals(column.getColumnKey(),"PRI")){
                String uuid=UUID.randomUUID().toString().replace("-","");
                value += ",'"+uuid+"' ";
                field += ","+column.getColumnName();
            }else{
                String javaColumnNameMin=StringUtils.camelMin(column.getColumnName());
                Object o=BeanUtil.getFieldValue(t,javaColumnNameMin);
                //对象不为空
                if(StringUtils.objectIsNotEmpty(o)){
                    field += ","+column.getColumnName();
                    value += ",#{t."+StringUtils.camelMin(column.getColumnName())+"} ";
                }
            }
        }
        field=field.substring(1);
        value=value.substring(1);
        String tableName=StringUtils.camelToUnderline(className); //表名
        return baseMapper.insert(t,tableName,field,value);
    }

    @Override
    public Integer update(T t) {
        setDefaultValu(t);
        String className=t.getClass().getSimpleName();
        List<Columns> columns=columnsService.selectColumnsByTableName(className);
        String sql="";//sql
        String filter="";//过滤
        for(Columns column: columns){
            String javaColumnNameMin=StringUtils.camelMin(column.getColumnName());

            if(StrUtil.equals(column.getColumnKey(),"PRI")){
                filter =column.getColumnName()+" = #{t."+javaColumnNameMin+"}";
                Object primaryKey=BeanUtil.getProperty(t,javaColumnNameMin);
                if(StringUtils.objectIsEmpty(primaryKey)){
                    return 0;
                }
            }else{
                sql+=" , "+column.getColumnName()+" = #{t."+javaColumnNameMin+"}";
            }
        }
        sql=sql.substring(2);
        String tableName=StringUtils.camelToUnderline(className); //表名
        return baseMapper.update(t,tableName,sql,filter);
    }

    @Override
    public Integer updateSelective(T t) {
        setDefaultValu(t);
        String className=t.getClass().getSimpleName();
        List<Columns> columns=columnsService.selectColumnsByTableName(className);
        String sql="";//sql
        String filter="";//过滤
        for(Columns column: columns){
            String javaColumnNameMin=StringUtils.camelMin(column.getColumnName());
            if(StrUtil.equals(column.getColumnKey(),"PRI")){
                filter =column.getColumnName()+" = #{t."+javaColumnNameMin+"}";
                Object primaryKey=BeanUtil.getProperty(t,javaColumnNameMin);
                if(StringUtils.objectIsEmpty(primaryKey)){
                    return 0;
                }
            }else{
                Object o=BeanUtil.getFieldValue(t,javaColumnNameMin);
                //对象不为空
                if(StringUtils.objectIsNotEmpty(o)){
                    sql+=" , "+column.getColumnName()+" = #{t."+javaColumnNameMin+"}";
                }

            }
        }
        if(sql.equals("")){
            return 1;
        }
        sql=sql.substring(2);
        String tableName=StringUtils.camelToUnderline(className); //表名
        return baseMapper.update(t,tableName,sql,filter);
    }


    @Override
    public Integer delete(String id) {
        String className=getClassName();;
        List<Columns> columns=columnsService.selectColumnsByTableName(className);
        String idName="";
        for(Columns column: columns){
            String javaColumnNameMin=StringUtils.camelMin(column.getColumnName());
            if(StrUtil.equals(column.getColumnKey(),"PRI")){
                idName=column.getColumnName();
            }
        }
        if(id.equals("")){
            return 0;
        }
        String tableName=StringUtils.camelToUnderline(className); //表名
        return baseMapper.delete(tableName,idName,id);
    }

    @Override
    public T read(String id) {
        String className=getClassName();;
        List<Columns> columns=columnsService.selectColumnsByTableName(className);
        String idName="";
        if(StrUtil.isEmpty(id)){
            return null;
        }
        for(Columns column: columns){
            String javaColumnNameMin=StringUtils.camelMin(column.getColumnName());
            if(StrUtil.equals(column.getColumnKey(),"PRI")){
                idName=column.getColumnName();
            }
        }
        String tableName=StringUtils.camelToUnderline(className); //表名
        Map<String,Object> map=baseMapper.read(tableName,idName,id);
        Set<String> s=new HashSet<String>();
        s.addAll(map.keySet());
        for(String k: s){
            map.put(k.toLowerCase(),map.get(k));
        }
        T t= ReflectUtil.newInstance(getTClass());
        BeanUtil.fillBeanWithMap(map,t,false);
        return t;
    }

    @Override
    public List<T> listByMap(Map<String, Object> map) {
        String className=getClassName();
        List<Columns> columns=columnsService.selectColumnsByTableName(className);
        String filter="";//过滤
        for(String javaColumnNameMin: map.keySet()){
            Object o=map.get(javaColumnNameMin);
            if(StringUtils.objectIsNotEmpty(o)){
                filter += " and " + StringUtils.camelToUnderline(javaColumnNameMin)+" = #{t."+javaColumnNameMin+"} ";
            }
        }
        if(!filter.equals("")){
            filter="  where 1=1 "+filter;
        }
        String tableName=StringUtils.camelToUnderline(className); //表名
        List<Map<String,Object>> lists=(baseMapper.listByMap(tableName,map,filter));
        List<T> result=new ArrayList<T>();
        if(lists==null || lists.size()==0){
            return result;
        }
        for(Map<String , Object> t:lists){
            T o=BeanUtil.toBean(t,getTClass());
            result.add(o);
        }
        return result;
    }

    @Override
    public List<T> listByMap(Map<String, Object> map, Page pages) {
        String className=getClassName();
        List<Columns> columns=columnsService.selectColumnsByTableName(className);
        String filter="";//过滤
        for(String javaColumnNameMin: map.keySet()){
            filter +=StringUtils.camelToUnderline(javaColumnNameMin)+" = #{t."+javaColumnNameMin+"}";
        }
        if(!filter.equals("")){
            filter="  where "+filter;
        }
        String tableName=StringUtils.camelToUnderline(className); //表名

        Page<T> result= PageHelper.startPage(pages.getPageNum(),pages.getPageSize(),null);
        List<Map<String,Object>> lists=baseMapper.listByMap(tableName,map,filter);
        if(lists==null || lists.size()==0){
            return result;
        }

        List<T> temp=new ArrayList<T>();
        for(Map<String , Object> t:lists){
            T o=BeanUtil.toBean(t,getTClass());
            temp.add(o);
        }
        result.clear();
        result.addAll(temp);
        return result;
    }

    @Override
    public void setDefaultValu(T t) {
        try {
            Object isDeleted=BeanUtil.getProperty(t,"isDeleted");
            if(StringUtils.objectIsEmpty(isDeleted)){
                BeanUtil.setProperty(t,"isDeleted","N");
            }

            BeanUtil.setProperty(t,"updateTime",new Date());

            Object updatedby=BeanUtil.getProperty(t,"updatedby");
            if(StringUtils.objectIsEmpty(updatedby)){
                BeanUtil.setProperty(t,"updatedby","");
            }

            Object createTime=BeanUtil.getProperty(t,"createTime");
            if(StringUtils.objectIsEmpty(createTime)){
                BeanUtil.setProperty(t,"createTime",new Date());
            }

            Object creator=BeanUtil.getProperty(t,"creator");
            if(StringUtils.objectIsEmpty(creator)){
                BeanUtil.setFieldValue(t,"creator","");
            }
        }catch (Exception e){

        }

    }

    @Override
    public boolean isExist(T t) {
        Map<String,Object> map=BeanUtil.beanToMap(t);
        List<T> list=this.listByMap(map);
        if(list !=null && list.size()>0){
            return true;
        }
        return false;
    }

    @Override
    public List<T> listAll() {
        return listByMap(new HashMap<String,Object>());
    }

    private String getClassName(){
        String typeName=((ParameterizedType)getClass().getGenericSuperclass()).getActualTypeArguments()[0].getTypeName();
        String [] typeNames=typeName.split("\\.");
        return typeNames[typeNames.length-1];
    }

    private Class<T> getTClass() {
        return (Class<T>) ((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[0];
    }
}
